var express = require('express');
var path = require('path');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');

var app = express();

var config = require('./config')

var exphbs = require('express-handlebars')
var handlebarsHelpers =require('./template_helpers')

app.set('views', path.join(__dirname, 'views'));
app.engine('html', exphbs({
    defaultLayout: 'default',
    extname: '.html',
    helpers:handlebarsHelpers
}));
app.set('view engine', 'html');

if (config.Env === 'prod') {
    app.enable('view cache');
}

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
    extended:true
}));
app.use(cookieParser());

require('./router').initRouterSystem(app)

app.use(express.static(path.join(__dirname, 'assets')));
app.use(express.static(path.join(__dirname, 'static_page')));

app.use(function(req, res, next) {
    var err = new Error('Not Found');
    err.status = 404;
    next(err);
});

if (config.Env === 'dev') {
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: {}
        });
    });
}else{
    console.log('run in dev mode')
    app.use(function(err, req, res, next) {
        res.status(err.status || 500);
        res.render('error', {
            message: err.message,
            error: err
        });
    });
}

app.listen(3001,function(){
    console.log('server start')
})